<template>
  <div class="upload">
    <a-upload
      :action="action"
      :headers="headers"
      list-type="picture-card"
      :file-list='fileList'
      @preview="handlePreview"
      @change="handleChange"
      :before-upload="beforeUpload"
      :remove="remove"
    >
      <div v-if="fileList.length < num">
        <a-icon type="plus" />
        <div class="ant-upload-text">
          Upload
        </div>
      </div>
    </a-upload>
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleCancel"
    >
      <img
        alt="example"
        style="width: 100%"
        :src="previewImage"
      />
    </a-modal>
  </div>
</template>

<script>
import storage from "store";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  props: {
    // 显示文件列表
    fileList: { type: Array, default: () => [] },
    num: {
      type: Number,
      default: 1,
    },
    //文件上传类型
    fileTypes: {
      type: Array,
      default: () => ["png", "PNG", "jpg", "JPG", "jpeg", "JPEG"],
    },
    fileTypesInfo: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 限制上传大小  单位M
    size: {
      type: Number,
      default: 100,
    },
  },

  data() {
    return {
      action: `${process.env.VUE_APP_API_BASE_URL}/cms/file/uploadImage`,
      previewVisible: false,
      previewImage: "",
      headers: {
        authorization: "authorization-text",
        source: this.$configs.source,
        tokenId: storage.get("Access-Token"),
      },
    };
  },
  watch: {
    fileList(value) {
      console.log("watch", value);
    },
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(info) {
      let { fileList } = info;
      if (info.file.status == "done") {
        if (info.file.response.code == 0) {
          this.$emit("success", info.file.response.data.url);
        }
      }
      this.$emit("successFile", [...fileList]);
      if (info.file.response) {
        if (info.file.response.code == 100003) {
          this.$message.error(response.data.msg);
          setTimeout(() => {
            storage.remove("Access-Token");
            storage.remove("User-Info");
            window.location.href = "/user/login";
          }, 2000);
        } else if (
          info.file.response.code != 0 &&
          info.file.response.code != 100003
        ) {
          this.fileList = [];
          this.$message.error(response.data.msg);
        }
      }
    },

    beforeUpload(info) {
      return new Promise((resolve, reject) => {
        if (!this.typeCheck(info.name)) {
          this.$message.info(`请上传以下格式${this.fileTypesInfo}文件`);
          return reject(false);
        }

        if (!this.sizeCheck(info.size)) {
          this.$message.info(`请上传${this.size}M以下的文件`);
          return reject(false);
        }

        return resolve(true);
      });
    },

    //, 检查文件大小
    sizeCheck(sizeFile) {
      if (this.size * 1024 * 1024 > sizeFile) {
        return true;
      } else {
        return false;
      }
    },
    // 检查文件类型
    typeCheck(name) {
      let arr = name.split(".");
      let type = arr[arr.length - 1];
      console.log(arr[arr.length - 1]);

      if (this.fileTypes.includes(type)) {
        return true;
      } else {
        return false;
      }
    },
    // 删除文件
    remove(file) {
      console.log(file);
    },
  },
};
</script>

<style>
</style>